

let Matrix = require('../matrix');
let shaderUtils = require('./shader_uitls');

let defVs = `attribute vec4 a_position;
attribute vec2 a_texCoord;

uniform mat4 a_mvpMatrix;
varying vec2 v_texCoord;

void main() {
    gl_Position = a_mvpMatrix * a_position;
    v_texCoord = a_texCoord;
}`;

let defFs = `precision mediump float;

varying vec2 v_texCoord;
uniform sampler2D u_sample0;
uniform vec3 u_color;
uniform float u_opacity;

void main() {
    // vec4 texColor =  vec4(u_color,1.0) * texture2D(u_sample0, v_texCoord);
    // texColor.rgb *= u_opacity;
    // gl_FragColor = texColor;
    
    // vec4 texColor = texture2D(u_sample0, v_texCoord);
    // texColor.rbg *= u_color;
    //
    // // texColor.rbg *= u_opacity;
    //  gl_FragColor = texColor;
     
     gl_FragColor = vec4(u_color,u_opacity) * texture2D(u_sample0, v_texCoord);
}
`;

let __id = 0;

let cfg = {
    Debug : false,
    _gl:null,
    _defaultTexture:null,
    _defaultShader:null,
    _pvMatrix:null,
    _gameApp:null,

    init(gl,gameApp){
        this._gl = gl;
        this._gameApp = gameApp;

        let projMatrix = Matrix.ortho(0,gameApp.width,0,gameApp.height);
        let viewMatrix = Matrix.defaultLookAt();
        this._pvMatrix = new Matrix();
        Matrix.mul(this._pvMatrix,projMatrix,viewMatrix);

        let _defaultShader = this._defaultShader = shaderUtils.initShaders(gl, defVs, defFs);
        _defaultShader.name = 'defaultShader';
        _defaultShader.bindAttrs([
            ['posHandle', 'a_position'],
            ['texPosHandle', 'a_texCoord'],
        ]);
        _defaultShader.bindUniforms([
            ['mvpHandle', 'a_mvpMatrix'],
            ['sampler0Handle', 'u_sample0'],
            ['colorHandle','u_color'],
            ['opacityHandle','u_opacity']
        ]);
    },

    genId(){
        return ++__id;
    },

    get pvMatrix(){
        return this._pvMatrix;
    },

    get gl(){
        return this._gl;
    },

    get defaultShader(){
        return this._defaultShader;
    },

    get defaultTexture(){
        return this._defaultTexture;
    },

    set defaultTexture(texture){
        if(this._defaultTexture !== texture){
            this._defaultTexture = texture;
        }
    },

    get gameApp(){
        return this._gameApp;
    },
};

module.exports = cfg;
